import time
import boto3
import logging

# [profile Qa]
# aws_access_key_id = "AKIASWZL2UIXMPQQ4NFT"
# aws_secret_access_key = "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"
#
# [profile Prod]
aws_access_key_id = "AKIAVGNWUKMQCF2NKKNR"
aws_secret_access_key = "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"

# aws 认证配置
aws_region = 'us-east-2'
dynamodb = boto3.client('dynamodb',
                        aws_access_key_id=aws_access_key_id,
                        aws_secret_access_key=aws_secret_access_key,
                        region_name=aws_region
                        )
logger = logging.getLogger('botocore')
logger.setLevel(logging.INFO)
# 添加处理器
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

global myDeviceLocationResponseMsg


def requestToDeviceLocation(did: str) -> str | Exception:
    global myDeviceLocationResponseMsg
    start_time = time.time()
    try:
        response = dynamodb.query(
            TableName='device-item-registration',
            IndexName="duuid-index",
            KeyConditionExpression='duuid = :v_duuid',
            ExpressionAttributeValues={
                ':v_duuid': {'S': did}
            }
        )
        if 'Items' in response and len(response['Items']) > 0:
            if "location_id" in response['Items'][0]:
                locationId = response['Items'][0]['location_id']['S']
                myDeviceLocationResponseMsg = locationId
                end_time = time.time()
                delta_time = end_time - start_time
                logger.info(f"Time taken by requestToDeviceLocation service in seconds = {delta_time}")
                return locationId
            else:
                logger.info(f"device-item-registration location_id not found for {did}")
                myDeviceLocationResponseMsg = ''
                return ''
        else:
            logger.info(f"device-item-registration not found for {did}")
            myDeviceLocationResponseMsg = ''
            return ''
    except Exception as e:
        myDeviceLocationResponseMsg = ''
        logger.exception("07:except is:")
        return e


if __name__ == "__main__":
    # did = '10c2ba08-0836-46ed-9c56-1dfdf1b7f5bd'
    # msg = requestToDeviceLocation(did)
    # print(f"msg is:{msg}")
    # print(f"myDeviceLocationResponseMsg is:{myDeviceLocationResponseMsg}")
    # print("执行完成！")

    # The code above is from device_info/device_item_registration.py
    global msg
    print(msg)